<template>
  <view class="orderlist_container">
    <view class="contenthead">
      <wd-card>
        <template #title>
          <wd-row>
            <wd-col :span="6">
              <view class="ordertitle">房间/区域</view>
            </wd-col>
            <wd-col :span="18">
              <view class="ordertitle">{{ orderdata?.roomOrAreaCode }}</view>
            </wd-col>
          </wd-row>
          <wd-row>
            <wd-col :span="6">
              <view class="ordertitle">单号</view>
            </wd-col>
            <wd-col :span="18">
              <view class="ordertitle">{{ orderdata?.orderNumber }}</view>
            </wd-col>
          </wd-row>
        </template>
        <wd-row>
          <wd-col :span="6">
            <view class="ordercontent">内容</view>
          </wd-col>
          <wd-col :span="18">
            <view class="ordercontent">{{ orderdata?.content }}</view>
          </wd-col>
        </wd-row>

        <wd-row>
          <wd-col :span="6">
            <view class="ordercontent">状态</view>
          </wd-col>
          <wd-col :span="18">
            <view class="ordercontent"
              ><wd-tag type="primary" mark>{{ statutext }}</wd-tag></view
            >
          </wd-col>
        </wd-row>
        <wd-row>
          <wd-col :span="6">
            <view class="ordercontent">类型</view>
          </wd-col>
          <wd-col :span="18">
            <view class="ordercontent">
              <wd-tag type="danger" mark v-if="orderdata?.enmergency"
                >紧急</wd-tag
              >
              <wd-tag type="primary" mark v-else>普通</wd-tag
              ><wd-tag type="primary" mark plain v-if="orderdata?.notification"
                >通知</wd-tag
              ></view
            >
          </wd-col>
        </wd-row>
      </wd-card>
    </view>
    <view class="time">
      <wd-card>
        <wd-row>
          <wd-col :span="6">
            <view class="create">发起人</view>
          </wd-col>
          <wd-col :span="18">
            <view class="create">{{ orderdata?.createUserName }}</view>
          </wd-col>
        </wd-row>
        <wd-row>
          <wd-col :span="6">
            <view class="ordertime">接单人</view>
          </wd-col>
          <wd-col :span="18">
            <view class="ordertime">{{ orderdata?.acceptedUserName }}</view>
          </wd-col>
        </wd-row>
        <wd-row>
          <wd-col :span="6">
            <view class="ordertime">创建时间</view>
          </wd-col>
          <wd-col :span="18">
            <view class="ordertime">{{
              formatDateTime(orderdata?.addTime)
            }}</view>
          </wd-col>
        </wd-row>
        <wd-row>
          <wd-col :span="6">
            <view class="ordertime">接单时间</view>
          </wd-col>
          <wd-col :span="18">
            <view class="ordertime">{{
              formatDateTime(orderdata?.acceptTime)
            }}</view>
          </wd-col>
        </wd-row>
        <wd-row>
          <wd-col :span="6">
            <view class="ordertime">完成时间</view>
          </wd-col>
          <wd-col :span="18">
            <view class="ordertime">{{
              formatDateTime(orderdata?.completeTime)
            }}</view>
          </wd-col>
        </wd-row>
        <wd-row>
          <wd-col :span="6">
            <view class="ordertime">接单时长</view>
          </wd-col>
          <wd-col :span="18">
            <view class="ordertime">{{ getaccetpduration(orderdata) }}</view>
          </wd-col>
        </wd-row>
        <wd-row>
          <wd-col :span="6">
            <view class="ordertime">完成时长</view>
          </wd-col>
          <wd-col :span="18">
            <view class="ordertime">{{ getcompletedduration(orderdata) }}</view>
          </wd-col>
        </wd-row>
        <wd-row>
          <wd-col :span="6">
            <view class="ordertime">接单等级</view>
          </wd-col>
          <wd-col :span="18">
            <view class="ordertime">{{ orderdata?.acceptedAlertLevel }}</view>
          </wd-col>
        </wd-row>
        <wd-row>
          <wd-col :span="6">
            <view class="ordertime">完成等级</view>
          </wd-col>
          <wd-col :span="18">
            <view class="ordertime">{{ orderdata?.completedAlertLevel }}</view>
          </wd-col>
        </wd-row>
      </wd-card>
    </view>
    <view class="countdown">
      <wd-card v-if="showdown">
        <wd-row>
          <wd-col :span="6">
            <view class="create">剩余时间</view>
          </wd-col>
          <wd-col :span="18">
            <wd-count-down :time="countdowvalue">
              <template #default="{ current }">
                <span class="custom-count-down">{{ current.hours }}</span>
                <span class="custom-count-down-colon">:</span>
                <span class="custom-count-down">{{ current.minutes }}</span>
                <span class="custom-count-down-colon">:</span>
                <span class="custom-count-down">{{ current.seconds }}</span>
              </template>
            </wd-count-down>
          </wd-col>
        </wd-row>
      </wd-card>
    </view>
    <view class="countdown">
      <wd-card v-if="orderdata?.orderStatu == OrderStatu.Canceled">
        <wd-row>
          <wd-col :span="6">
            <view class="create">取消原因</view>
          </wd-col>
          <wd-col :span="18"> {{ orderdata.cancellationReason }}</wd-col>
        </wd-row>
      </wd-card>
    </view>
    <view class="countdown">
      <wd-card v-if="orderdata?.orderStatu == OrderStatu.Paused">
        <wd-row>
          <wd-col :span="6">
            <view class="create">暂停原因</view>
          </wd-col>
          <wd-col :span="18"> {{ orderdata.pauseReason }}</wd-col>
        </wd-row>
      </wd-card>
    </view>
    <!-- 耗材内容 -->
    <view class="countdown">
      <wd-card v-if="consumables?.length > 0">
        <wd-row v-for="item in consumables" :key="item.id" class="consumables">
          <wd-col :span="18">
            {{ item.consumabDto.showName }} * {{ item.quantity }}</wd-col
          >
        </wd-row>
      </wd-card>
    </view>
    <view class="fixed-button">
      <wd-button
        type="success"
        size="small"
        v-if="showtrans"
        @click="showActions"
        >转单</wd-button
      >
      <wd-button size="small" v-if="showpaus" @click="pauseclick">{{
        btnpaused
      }}</wd-button>
      <wd-button
        type="warning"
        size="small"
        v-if="showcancel"
        @click="calcelclick"
        >取消</wd-button
      >
      <wd-button
        type="error"
        size="small"
        @click="consumablesclick"
        v-if="orderdata?.orderStatu != OrderStatu.Canceled"
        >耗材</wd-button
      >
      <wd-button
        type="success"
        size="small"
        v-if="showbtn"
        @click="handelAcceptOrder(orderdata?.id!)"
        >{{ btntext }}</wd-button
      >
    </view>
    <wd-message-box />
    <wd-action-sheet
      v-model="show"
      :actions="actions"
      @close="close"
      @select="select"
      z-index="1099"
      :safe-area-inset-bottom="true"
    />
    <wd-toast />
  </view>
</template>

<script setup lang="ts">
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref, computed } from 'vue'
import { useToast } from '@/uni_modules/wot-design-uni'
import {
  AcceptOrder,
  CompleteOrder,
  GetOrderByID,
  GetServerRuntime,
  CanceledOrder,
  PausedOrder,
  ResumedOrder,
  TransferOrder,
  getconsumablesbyid
} from '@/API/order/index'
import {
  OrderStatu,
  type workOrderDto,
  type CanceledOrPausedDto,
  type TransferDto,
  type OrderConsumabsDto
} from '@/API/order/types'
import { GetActivePhonesByPhoneID } from '@/API/phone/index'
import type { PhoneDto } from '@/API/phone/types'
import { useMessage } from '@/uni_modules/wot-design-uni'
import type { Action } from '@/uni_modules/wot-design-uni/components/wd-action-sheet/types'
import { useUserStore } from '@/store/user/index'
import { usePageStateStore } from '@/store/PageSate/index'
import moment from 'moment'
const toast = useToast()
const phonslist = ref<PhoneDto[]>([])
const message = useMessage()
const orderid = ref('')
const pausereson = ref('')
const show = ref(false)
const PageStateStore = usePageStateStore()
const orderdata = ref<workOrderDto>()
const userStore = useUserStore()
const consumables = ref<OrderConsumabsDto[]>([])
const showdown = computed(() => {
  return (
    orderdata.value?.orderStatu == OrderStatu.Created ||
    orderdata.value?.orderStatu == OrderStatu.Accepted ||
    orderdata.value?.orderStatu == OrderStatu.Transfered ||
    orderdata.value?.orderStatu == OrderStatu.Resumed
  )
})

const btntext = ref('接单')
const btnpaused = ref('暂停')
const statutext = computed(() => {
  switch (orderdata.value?.orderStatu) {
    case OrderStatu.Created:
      btntext.value = '接单'
      return '创建'

    case OrderStatu.Paused:
      btnpaused.value = '恢复'
      return '暂停'
    case OrderStatu.Accepted:
      btnpaused.value = '暂停'
      btntext.value = '完成'
      return '已接单'
    case OrderStatu.Resumed:
      btntext.value = '完成'
      return '已恢复'
    case OrderStatu.Transfered:
      return '转单'
    case OrderStatu.Completed:
      return '完成'
    case OrderStatu.Canceled:
      return '取消'
  }
})

const Loadorderdata = async () => {
  const usestore = useUserStore()
  const result = await GetOrderByID(orderid.value, usestore.phoneid)
  orderdata.value = result
  getcountdowvalue(orderdata.value)
  // console.log(orderdata.value)
}

const countdowvalue = ref(0)
const showbtn = computed(() => {
  return (
    (orderdata.value?.orderStatu == OrderStatu.Created ||
      orderdata.value?.orderStatu == OrderStatu.Accepted ||
      orderdata.value?.orderStatu == OrderStatu.Transfered ||
      orderdata.value?.orderStatu == OrderStatu.Resumed) &&
    orderdata.value?.canAction
  )
})

const showpaus = computed(() => {
  return (
    (orderdata.value?.orderStatu == OrderStatu.Accepted ||
      orderdata.value?.orderStatu == OrderStatu.Paused) &&
    orderdata.value?.canAction
  )
})

const showtrans = computed(() => {
  return (
    orderdata.value?.orderStatu == OrderStatu.Accepted &&
    orderdata.value?.canAction
  )
})

const showcancel = computed(() => {
  return (
    orderdata.value?.orderStatu == OrderStatu.Accepted ||
    (orderdata.value?.orderStatu == OrderStatu.Transfered &&
      orderdata.value?.canAction)
  )
})
const getcountdowvalue = async (data?: workOrderDto) => {
  if (
    data?.orderStatu == OrderStatu.Created ||
    data?.orderStatu == OrderStatu.Transfered ||
    data?.orderStatu == OrderStatu.Accepted ||
    data?.orderStatu == OrderStatu.Resumed
  ) {
    const servernow = await GetServerRuntime()
    const now = moment(servernow)
    //接单剩余时长
    if (
      data?.orderStatu == OrderStatu.Created ||
      data?.orderStatu == OrderStatu.Transfered
    ) {
      var addtimeMoment = moment(data?.addTime)
      var duration = now.diff(addtimeMoment, 'seconds')
      const acceptduration = data?.acceptDuration
      if (data?.orderStatu == OrderStatu.Transfered) {
        addtimeMoment = moment(data?.transferedTime)
        duration = now.diff(addtimeMoment, 'seconds')
      }
      // console.log(duration, acceptduration * 60)
      if (duration < acceptduration * 60) {
        countdowvalue.value = (acceptduration * 60 - duration) * 1000
      } else {
        countdowvalue.value = 0
      }
    }
    if (data?.orderStatu == OrderStatu.Accepted) {
      const acceptTimeMoment = moment(data?.acceptTime)
      const duration = now.diff(acceptTimeMoment, 'seconds')
      const conpleteduration = data?.completeDuration
      console.log(duration, conpleteduration * 60)
      if (duration < conpleteduration * 60) {
        countdowvalue.value = (conpleteduration * 60 - duration) * 1000
      } else {
        countdowvalue.value = 0
      }
    }
    if (data?.orderStatu == OrderStatu.Resumed) {
      const acceptTimeMoment = moment(data?.resumedTime)
      const duration = now.diff(acceptTimeMoment, 'seconds')
      const conpleteduration = data?.completeDuration
      console.log(duration, conpleteduration * 60)
      if (duration < conpleteduration * 60) {
        countdowvalue.value = (conpleteduration * 60 - duration) * 1000
      } else {
        countdowvalue.value = 0
      }
    }
  }
}
const formatDateTime = (datetime: any) => {
  if (!datetime) {
    return '-'
  }
  return moment(datetime).format('YYYY-MM-DD HH:mm:ss')
}
const formatDurationInSeconds = (seconds: number) => {
  const hours = Math.floor(seconds / 3600)
  seconds %= 3600
  const minutes = Math.floor(seconds / 60)
  seconds %= 60

  // 确保每部分至少为两位数，不足则前面补0
  const formattedHours = String(hours).padStart(2, '0')
  const formattedMinutes = String(minutes).padStart(2, '0')
  const formattedSeconds = String(seconds).padStart(2, '0')

  return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`
}
const getaccetpduration = (data?: workOrderDto) => {
  if (data?.acceptTime && data?.addTime) {
    const addTimeMoment = moment(data?.addTime)
    const acceptTimeMoment = moment(data?.acceptTime)

    // 计算两个时间的差值，moment 提供了直接的方法来处理时间差
    const duration = acceptTimeMoment.diff(addTimeMoment, 'seconds') // 直接得到分钟差
    return formatDurationInSeconds(duration)
  } else {
    return null // 或者根据需要处理
  }
}
/**
 * @description: 获取完成时长 可能还要处理 转单、取消、暂停等
 * @param {workOrderDto} data
 * @return {*}
 */
const getcompletedduration = (data?: workOrderDto) => {
  if (data?.completeTime && data?.acceptTime) {
    const acceptTimeMoment = moment(data?.acceptTime)
    const completeTimeMoment = moment(data?.completeTime)

    // 计算两个时间的差值，moment 提供了直接的方法来处理时间差
    const duration = completeTimeMoment.diff(acceptTimeMoment, 'seconds') // 直接得到分钟差

    return formatDurationInSeconds(duration)
  } else {
    return null // 或者根据需要处理
  }
}

const handelAcceptOrder = async (orderid: string) => {
  if (
    orderdata.value?.orderStatu == OrderStatu.Created ||
    orderdata.value?.orderStatu == OrderStatu.Transfered
  ) {
    const result = await AcceptOrder(orderid, userStore.phoneid)
    if (result.code != '200') {
      toast.error('接单失败,工单状态不正确')
    }
    await Loadorderdata()
  } else if (
    orderdata.value?.orderStatu == OrderStatu.Accepted ||
    orderdata.value?.orderStatu == OrderStatu.Resumed
  ) {
    const result = await CompleteOrder(orderid, userStore.phoneid)
    if (result.code != '200') {
      toast.error('完成失败,工单状态不正确')
    }
    await Loadorderdata()
  }
}

const showActions = async () => {
  show.value = true

  const result = await GetActivePhonesByPhoneID(userStore.phoneid)
  phonslist.value = result

  actions.value = ToSelectActions(result)
  // console.log(phonslist.value)
}
const close = () => {
  show.value = false
}

const ToSelectActions = (phones: PhoneDto[]): Action[] => {
  return phones.map(phone => ({
    name: phone.name,
    subname: phone.phoneNumber,
    disabled: false,
    loading: false,
    color: '#000'
  }))
}
const actions = ref<Action[]>([])
const select = ({ item, index }: { item: Action; index: number }) => {
  // console.log(`当前选中项: ${item.name}, 下标: ${index}`)
  //console.log(phonslist.value[index])
  var phone = phonslist.value[index]
  message
    .confirm({
      msg: `确认转单给${item.name}`,
      title: '提示'
    })
    .then(async () => {
      const data = ref<TransferDto>({
        actionId: userStore.phoneid,
        transferedId: phone.id
      })
      const result = await TransferOrder(orderid.value, data.value)

      if (result.code != '200') {
        toast.error('转单失败,工单状态不正确')
      }
      await Loadorderdata()
    })
    .catch(() => {
      console.log('点击了取消按钮')
    })
}
onLoad(async option => {
  PageStateStore.detialstate = true
  orderid.value = option!.id
  await Loadorderdata()
  // await loaddata()
})
onShow(async () => {
  if (orderid.value) {
    await loaddata()
  }
})

const consumablesclick = () => {
  uni.navigateTo({
    url: `/pages/consumables/consumables?id=${orderid.value}`
  })
}
const pauseclick = () => {
  if (orderdata.value?.orderStatu == OrderStatu.Paused) {
    message
      .confirm({
        msg: '是否恢复',
        title: '提示'
      })
      .then(async () => {
        const result = await ResumedOrder(orderid.value, userStore.phoneid)
        if (result.code != '200') {
          toast.error('恢复失败,工单状态不正确')
        }
        await Loadorderdata()
      })
      .catch(() => {
        console.log('点击了取消按钮')
      })
  } else {
    message
      .prompt({
        title: '请输入原因',
        inputValue: pausereson.value
      })
      .then(async resp => {
        console.log(resp)
        const data = ref<CanceledOrPausedDto>({
          createId: userStore.phoneid,
          reason: resp.value as string
        })
        const result = await PausedOrder(orderid.value, data.value)
        if (result.code != '200') {
          toast.error('暂停失败,工单状态不正确')
        }
        await Loadorderdata()
      })
      .catch(error => {
        console.log('error:', error)
      })
  }
}
const calcelclick = () => {
  message
    .prompt({
      title: '请输入原因',
      inputValue: pausereson.value
    })
    .then(async resp => {
      console.log(resp)
      const data = ref<CanceledOrPausedDto>({
        createId: userStore.phoneid,
        reason: resp.value as string
      })
      const result = await CanceledOrder(orderid.value, data.value)
      if (result.code != '200') {
        toast.error('取消失败,工单状态不正确')
      }
      await Loadorderdata()
    })
    .catch(error => {
      console.log('error:', error)
    })
}

const loaddata = async () => {
  const result = await getconsumablesbyid(orderid.value)
  consumables.value = result
}
</script>

<style lang="scss" scoped>
:deep(.wd-card) {
  box-shadow: var(
    --wot-card-shadow-color,
    0px 2px 5px 0px rgba(0, 0, 0, 0.2)
  ) !important;
}

:deep(.wd-tag__text) {
  font-size: 30rpx;
}

:deep(.wd-tag) {
  margin-left: 10rpx;
}

:deep(.wd-button) {
  margin-left: 10rpx;
}

:deep(.wd-button__text) {
  font-size: 35rpx;
}

/* 增强action-sheet样式 */
:deep(.wd-action-sheet) {
  padding-bottom: calc(150rpx + constant(safe-area-inset-bottom)) !important;
  padding-bottom: calc(150rpx + env(safe-area-inset-bottom)) !important;
}

.orderlist_container {
  margin-top: 30rpx;

  .contenthead {
    .ordertitle {
      font-weight: bold;
      font-size: 28rpx;
      justify-content: left;
      align-items: center;
      width: 100%;
      margin-bottom: 10px;
    }

    .ordercontent {
      font-weight: bold;
      font-size: 28rpx;
      justify-content: left;
      align-items: center;
      width: 100%;

      margin-bottom: 10px;
    }
  }

  .time {
    .create {
      margin-top: 15rpx;
      font-size: 28rpx;
      justify-content: left;
      align-items: center;
      width: 100%;
      margin-bottom: 10px;
    }
    .ordertime {
      font-size: 28rpx;
      justify-content: left;
      align-items: center;
      width: 100%;

      margin-bottom: 10px;
    }
  }

  .countdown {
    .ordertime {
      font-size: 28rpx;
      justify-content: left;
      align-items: center;
      width: 100%;

      margin-bottom: 10px;
    }
    :deep(.wd-card) {
      padding: 10rpx 20rpx; /* 调整卡片内边距 */
    }

    .custom-count-down {
      display: inline-block;
      width: 22px;
      font-size: 30rpx;
      text-align: center;
      border-radius: 2px;
      color: #fff;
      background-color: #f0883a;
    }

    .custom-count-down-colon {
      display: inline-block;
      margin: 0 4px;
      color: #f0883a;
    }
    .consumables {
      margin-top: 15rpx;
    }
  }

  .fixed-button {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #fff;
    padding: 20rpx 30rpx; /* 增加左右内边距 */
    box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.06);
    z-index: 999; /* 确保在弹层上方 */
    display: flex;
    justify-content: flex-end;
    gap: 20rpx; /* 按钮间距 */
    /* 适配安全区域 */
    padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  }

  .btn {
    margin-left: 10rpx;
  }
}
</style>
